import { 
  Card, 
  Tag, 
  Button, 
  message,
  Modal,
  Image,
  Typography,
  Spin,
  Divider,
  Space,
  Drawer,
  Checkbox,
  Input,
  Collapse
} from 'antd';
import * as React from 'react';
import { useState, useEffect, useCallback } from 'react';
import { 
  HeartOutlined,
  HeartFilled,
  RotateRight,
  CheckCircle,
  XCircle,
  PlusOutlined,
  DeleteOutlined,
  ArrowLeftOutlined,
  FireOutlined
} from '@ant-design/icons';
import { clientApi } from '../../services/api';
import { useNavigate } from 'react-router-dom';
import LoginModal from '../../components/LoginModal';
import { saveUser, getUser, removeUser } from '../../utils/auth';

const { Title, Text, Paragraph } = Typography;
const { Panel } = Collapse;

const RandomPage = () => {
  const navigate = useNavigate();
  const [dishes, setDishes] = useState([]);
  const [categories, setCategories] = useState([]);
  const [tags, setTags] = useState([]);
  const [loading, setLoading] = useState(false);
  
  // 抽卡状态
  const [isDrawing, setIsDrawing] = useState(false);
  const [selectedDish, setSelectedDish] = useState(null);
  const [showResult, setShowResult] = useState(false);
  const [drawingIndex, setDrawingIndex] = useState(0);
  const [drawingDishes, setDrawingDishes] = useState([]);
  
  // 用户相关状态
  const [user, setUser] = useState(getUser());
  const [loginVisible, setLoginVisible] = useState(false);
  const [favoriteIds, setFavoriteIds] = useState([]);
  
  // 自定义规则状态
  const [customRules, setCustomRules] = useState({
    categories: [],
    tags: [],
    selectedDishes: [],
    searchKeyword: ''
  });

  // 抽屉状态
  const [ruleDrawerVisible, setRuleDrawerVisible] = useState(false);
  const [filteredDishes, setFilteredDishes] = useState([]);
  const [loadingDishes, setLoadingDishes] = useState(false);

  const loadCategories = async () => {
    try {
      const response = await clientApi.getCategories();
      setCategories(response.data || []);
    } catch (error) {
      console.error('加载分类失败:', error);
    }
  };

  // 加载符合条件的菜品
  const loadFilteredDishes = async () => {
    setLoadingDishes(true);
    try {
      const { categories, tags, searchKeyword } = customRules;
      const params = {};
      if (categories.length > 0) params.categoryIds = categories;
      if (tags.length > 0) params.tagIds = tags;
      if (searchKeyword) params.name = searchKeyword;

      const response = await clientApi.getDishes(params);
      setFilteredDishes(response.data || []);
    } catch (error) {
      console.error('加载菜品失败:', error);
      message.error('加载菜品失败');
    } finally {
      setLoadingDishes(false);
    }
  };

  // 处理分类选择
  const handleCategoryChange = (categoryId, checked) => {
    setCustomRules(prev => ({
      ...prev,
      categories: checked
        ? [...prev.categories, categoryId]
        : prev.categories.filter(id => id !== categoryId)
    }));
  };

  // 处理标签选择
  

  // 处理菜品选择
  const handleDishSelect = (dishId, checked) => {
    setCustomRules(prev => ({
      ...prev,
      selectedDishes: checked
        ? [...prev.selectedDishes, dishId]
        : prev.selectedDishes.filter(id => id !== dishId)
    }));
  };

  // 处理搜索
  const handleSearchChange = (e) => {
    setCustomRules(prev => ({
      ...prev,
      searchKeyword: e.target.value
    }));
  };

  // 应用规则并关闭抽屉
  const applyCustomRules = () => {
    loadFilteredDishes();
    setRuleDrawerVisible(false);
  };

  // 清除规则
  

  // 打开抽屉时加载菜品
  useEffect(() => {
    if (ruleDrawerVisible) {
      loadFilteredDishes();
    }
  }, [ruleDrawerVisible]);

  const loadTags = async () => {
    try {
      const response = await clientApi.getTags();
      setTags(response.data || []);
    } catch (error) {
      console.error('加载标签失败:', error);
    }
  };

  const loadFavoriteIds = useCallback(async () => {
    if (!user) return;
    try {
      const response = await clientApi.getFavoriteIds(user.id);
      setFavoriteIds(response.data || []);
    } catch (error) {
      console.error('加载收藏列表失败:', error);
    }
  }, [user]);

  useEffect(() => {
    loadCategories();
    loadTags();
    if (user) {
      loadFavoriteIds();
    }
  }, [user, loadFavoriteIds]);

  const handleLogin = (userInfo) => {
    setUser(userInfo);
    saveUser(userInfo);
    setLoginVisible(false);
    message.success(`欢迎回来，${userInfo.nickname}！`);
  };

  const handleLogout = () => {
    setUser(null);
    removeUser();
    setFavoriteIds([]);
    message.success('已退出登录');
  };

  const toggleFavorite = async (dish) => {
    if (!user) {
      setLoginVisible(true);
      return;
    }

    try {
      const isFav = favoriteIds.includes(dish.id);
      if (isFav) {
        await clientApi.removeFavorite(user.id, dish.id);
        setFavoriteIds(prev => prev.filter(id => id !== dish.id));
        message.success('已取消收藏');
      } else {
        await clientApi.addFavorite(user.id, dish.id);
        setFavoriteIds(prev => [...prev, dish.id]);
        message.success('已添加收藏');
      }
    } catch (error) {
      message.error(error.message || '操作失败');
    }
  };

  const startDrawing = async () => {
    if (!user) {
      setLoginVisible(true);
      return;
    }

    setIsDrawing(true);
    setShowResult(false);
    setSelectedDish(null);
    setDrawingIndex(0);

    try {
      const { selectedDishes, categories, tags } = customRules;
      let randomDish;
      let dishesForAnimation = [];

      if (selectedDishes.length > 0) {
        // 从选中的菜品中随机选择一个
        const response = await clientApi.getRandomDishes([], [], selectedDishes);
        if (response.data && response.data.length > 0) {
          dishesForAnimation = response.data;
          // 如果选中的菜品不足20个，则重复填充以获得更好的动画效果
          while (dishesForAnimation.length < 20) {
            dishesForAnimation = [...dishesForAnimation, ...response.data];
          }
          // 随机排序
          dishesForAnimation.sort(() => 0.5 - Math.random());
          // 选择一个随机菜品作为最终结果
          randomDish = dishesForAnimation[Math.floor(Math.random() * dishesForAnimation.length)];
        }
      } else {
        // 根据分类和标签获取20个菜品用于动画
        const response = await clientApi.getRandomDishes(categories, tags);
        if (response.data && response.data.length > 0) {
          dishesForAnimation = response.data;
          // 随机排序
          dishesForAnimation.sort(() => 0.5 - Math.random());
          // 选择一个随机菜品作为最终结果
          randomDish = dishesForAnimation[Math.floor(Math.random() * dishesForAnimation.length)];
        }
      }

      if (randomDish) {
        setDrawingDishes(dishesForAnimation);
        setSelectedDish(randomDish);

        // 抽卡动画，每0.08秒切换一次卡片
        const interval = setInterval(() => {
          setDrawingIndex(prevIndex => {
            const newIndex = (prevIndex + 1) % dishesForAnimation.length;
            return newIndex;
          });
        }, 80);

        // 3秒后停止动画并显示结果
        setTimeout(() => {
          clearInterval(interval);
          setShowResult(true);
          setIsDrawing(false);
        }, 3000);
      } else {
        message.warning('没有符合条件的菜品');
        setIsDrawing(false);
      }
    } catch (error) {
      message.error('抽卡失败，请重试');
      setIsDrawing(false);
    }
  };

  const drawAgain = () => {
    setShowResult(false);
    setSelectedDish(null);
    startDrawing();
  };

  const acceptDish = () => {
    message.success('恭喜！开始享受美食吧！');
    setShowResult(false);
    setSelectedDish(null);
  };

  const rejectDish = () => {
    drawAgain();
  };

  const getCategoryName = (categoryId) => {
    const category = categories.find(c => c.id === categoryId);
    return category ? category.name : '';
  };

  const getTagName = (tagId) => {
    const tag = tags.find(t => t.id === tagId);
    return tag ? tag.name : '';
  };

  const handleTagChange = (tagId, checked, type = 'include') => {
    if (type === 'include') {
      setCustomRules(prev => ({
        ...prev,
        tags: checked
          ? [...prev.tags, tagId]
          : prev.tags.filter(id => id !== tagId)
      }));
    } else {
      setCustomRules(prev => ({
        ...prev,
        excludeTags: checked
          ? [...prev.excludeTags, tagId]
          : prev.excludeTags.filter(id => id !== tagId)
      }));
    }
  };

  const clearRules = () => {
    setCustomRules({
      categories: [],
      tags: [],
      excludeTags: []
    });
  };

  if (loading) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        minHeight: '60vh'
      }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div style={{ background: 'var(--secondary-bg)', minHeight: '100vh' }}>
      {/* 顶部标题区域 */}
      <div style={{
        background: 'var(--primary-bg)',
        padding: '60px 20px 30px',
        textAlign: 'center',
        borderBottom: '1px solid var(--border-light)',
        position: 'relative'
      }}>
        <Button
          type="text"
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate(-1)}
          style={{
            position: 'absolute',
            top: '20px',
            left: '20px',
            color: 'var(--text-tertiary)',
            fontSize: '18px',
            padding: '8px',
            borderRadius: '50%'
          }}
        />
        
        <Title level={2} style={{
          margin: 0,
          fontSize: '28px',
          fontWeight: 700,
          color: 'var(--text-primary)',
          lineHeight: 1.2
        }}>
          今日吃什么
        </Title>
        <Text style={{
          color: 'var(--text-secondary)',
          fontSize: '16px',
          marginTop: '8px',
          display: 'block'
        }}>
          让命运决定你的下一餐
        </Text>
      </div>

      <div style={{ padding: '20px' }}>
        {/* 抽卡区域 */}
        <div style={{
          position: 'relative',
          background: 'var(--primary-bg)',
          borderRadius: '20px',
          padding: '40px 20px',
          textAlign: 'center',
          marginBottom: '24px',
          boxShadow: 'var(--shadow-medium)',
          overflow: 'hidden',
          height: '400px'
        }}>
          {/* 顶部盖子 */}
          <div
            className="lid top-lid"
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              height: isDrawing ? '30%' : '52%',
              background: '#f5f5f7',
              transition: 'height 0.8s cubic-bezier(0.33, 1, 0.68, 1)',
              zIndex: 10
            }}
          />

          {/* 底部盖子 */}
          <div
            className="lid bottom-lid"
            style={{
              position: 'absolute',
              bottom: 0,
              left: 0,
              right: 0,
              height: isDrawing ? '40%' : '48%',
              background: '#f5f5f7',
              transition: 'height 0.8s cubic-bezier(0.33, 1, 0.68, 1)',
              zIndex: 10
            }}
          />

          {/* 中间抽卡按钮和横线 */}
          <div
            style={{
              position: 'absolute',
              top: '50%',
              left: 0,
              right: 0,
              transform: 'translateY(-50%)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              opacity: isDrawing ? 0 : 1,
              transition: 'opacity 0.8s cubic-bezier(0.33, 1, 0.68, 1)',
              zIndex: 20
            }}
          >
            <div style={{
              height: '1px',
              width: '30%',
              background: '#d2d2d7'
            }} />
            <div
              style={{
                width: '80px',
                height: '80px',
                borderRadius: '50%',
                background: '#1d1d1f',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                margin: '0 16px',
                cursor: isDrawing ? 'default' : 'pointer'
              }}
              onClick={!isDrawing ? startDrawing : undefined}
            >
              <Text style={{
                color: '#fff',
                fontSize: '24px',
                fontWeight: 'bold'
              }}>
                抽
              </Text>
            </div>
            <div style={{
              height: '1px',
              width: '30%',
              background: '#d2d2d7'
            }} />
          </div>

          {/* 抽卡区域 */}
          <div
            style={{
              position: 'absolute',
              top: '30%',
              left: '10%',
              right: '10%',
              bottom: '40%',
              display: isDrawing ? 'flex' : 'none',
              alignItems: 'center',
              justifyContent: 'center',
              zIndex: 5
            }}
          >
            {drawingDishes.length > 0 && (
              <div
                style={{
                  width: '100%',
                  height: '100%',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  perspective: '1000px'
                }}
              >
                <Card
                  hoverable
                  className="drawing-card"
                  cover={
                    <Image
                      alt={drawingDishes[drawingIndex]?.name || ''}
                      src={drawingDishes[drawingIndex]?.imageUrl || ''}
                      preview={false}
                      style={{
                        width: '100%',
                        height: '200px',
                        objectFit: 'cover',
                        borderRadius: '14px 14px 0 0'
                      }}
                    />
                  }
                  style={{
                    width: '80%',
                    borderRadius: '14px',
                    boxShadow: '0 10px 20px rgba(0, 0, 0, 0.1)',
                    transformStyle: 'preserve-3d',
                    transition: 'transform 0.08s ease',
                    transform: `rotateY(${Math.random() * 10 - 5}deg) rotateX(${Math.random() * 10 - 5}deg)`
                  }}
                >
                  <Card.Meta
                    title={
                      <Text style={{ fontSize: '18px', fontWeight: 600 }}>
                        {drawingDishes[drawingIndex]?.name || '加载中...'}
                      </Text>
                    }
                    description={
                      <Text style={{ fontSize: '14px', color: '#666' }}>
                        {getCategoryName(drawingDishes[drawingIndex]?.categoryId) || ''}
                      </Text>
                    }
                  />
                </Card>
              </div>
            )}
          </div>
          {/* 结果展示区域 */}
          <div
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              display: showResult ? 'flex' : 'none',
              alignItems: 'center',
              justifyContent: 'center',
              padding: '20px',
              zIndex: 20
            }}
          >
            <div style={{
              width: '80%',
              padding: '20px',
              borderRadius: '14px',
              background: '#fff',
              boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)',
              textAlign: 'center'
            }}>
              <Text style={{
                fontSize: '18px',
                fontWeight: 'bold',
                marginBottom: '10px'
              }}>
                抽中菜品
              </Text>
              <Image
                alt={selectedDish?.name || ''}
                src={selectedDish?.imageUrl || ''}
                preview={false}
                style={{
                  width: '120px',
                  height: '120px',
                  objectFit: 'cover',
                  borderRadius: '10px',
                  marginBottom: '15px'
                }}
              />
              <Text style={{
                fontSize: '24px',
                fontWeight: 'bold',
                marginBottom: '10px'
              }}>
                {selectedDish?.name || ''}
              </Text>
              <Text style={{
                fontSize: '14px',
                color: '#666',
                marginBottom: '15px'
              }}>
                {getCategoryName(selectedDish?.categoryId) || ''}
              </Text>
              <div style={{
                display: 'flex',
                flexWrap: 'wrap',
                gap: '8px',
                justifyContent: 'center',
                marginBottom: '20px'
              }}>
                {selectedDish?.tags?.map((tag, index) => (
                  <span
                    key={index}
                    style={{
                      backgroundColor: '#f0f0f0',
                      borderRadius: '12px',
                      padding: '4px 12px',
                      fontSize: '12px',
                      color: '#666'
                    }}>
                    {getTagName(tag)}
                  </span>
                ))}
              </div>
              <div style={{
                display: 'flex',
                justifyContent: 'center',
                gap: '16px'
              }}>
                <Button
                  size="large"
                  onClick={() => {
                    // 拒绝菜品逻辑
                    if (selectedDish) {
                      clientApi.rejectDish({ dishId: selectedDish.id, reason: '不喜欢' });
                    }
                    drawAgain();
                  }}
                  style={{
                    width: '120px',
                    height: '40px',
                    borderRadius: '20px',
                    fontSize: '14px',
                    borderColor: '#d2d2d7',
                    color: '#666'
                  }}
                >
                  拒绝
                </Button>
                <Button
                  type="primary"
                  size="large"
                  onClick={() => {
                    // 接受菜品逻辑
                    if (selectedDish) {
                      clientApi.acceptDish({ dishId: selectedDish.id });
                    }
                    drawAgain();
                  }}
                  style={{
                    width: '120px',
                    height: '40px',
                    borderRadius: '20px',
                    fontSize: '14px',
                    backgroundColor: '#1d1d1f'
                  }}
                >
                  接受
                </Button>
              </div>
            </div>
          </div>
        </div>

        {/* 自定义规则按钮 */}
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => setRuleDrawerVisible(true)}
          style={{
            width: '100%',
            borderRadius: '20px',
            padding: '12px',
            marginTop: '20px',
            background: 'var(--primary-bg)',
            color: 'var(--text-primary)',
            border: '1px solid var(--border-light)'
          }}
        >
          自定义筛选规则
        </Button>

        {/* 自定义规则抽屉 */}
        <Drawer
          title="自定义筛选规则"
          placement="bottom"
          onClose={() => setRuleDrawerVisible(false)}
          open={ruleDrawerVisible}
          size="large"
          maskClosable={false}
          style={{
            height: '60%',
            borderTopLeftRadius: '20px',
            borderTopRightRadius: '20px',
            overflow: 'hidden'
          }}
          footer={
            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '16px' }}>
              <Button onClick={clearRules}>清除规则</Button>
              <Button type="primary" onClick={applyCustomRules}>应用规则</Button>
            </div>
          }
        >
          <div style={{ padding: '16px', overflowY: 'auto', height: 'calc(100% - 55px)' }}>
            {/* 分类选择 */}
            <div style={{ marginBottom: '24px' }}>
              <Text style={{ fontSize: '16px', fontWeight: 500, marginBottom: '12px', display: 'block' }}>
                选择分类
              </Text>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
                {categories.map(category => (
                  <Checkbox
                    key={category.id}
                    checked={customRules.categories.includes(category.id)}
                    onChange={(e) => handleCategoryChange(category.id, e.target.checked)}
                    style={{
                      padding: '8px 16px',
                      borderRadius: '16px',
                      border: '1px solid var(--border-light)',
                      backgroundColor: customRules.categories.includes(category.id) ? 'var(--accent-primary)' : 'var(--primary-bg)',
                      color: customRules.categories.includes(category.id) ? '#fff' : 'var(--text-primary)'
                    }}
                  >
                    {category.name}
                  </Checkbox>
                ))}
              </div>
            </div>

            {/* 标签选择 */}
            <div style={{ marginBottom: '24px' }}>
              <Text style={{ fontSize: '16px', fontWeight: 500, marginBottom: '12px', display: 'block' }}>
                选择标签
              </Text>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
                {tags.map(tag => (
                  <Checkbox
                    key={tag.id}
                    checked={customRules.tags.includes(tag.id)}
                    onChange={(e) => handleTagChange(tag.id, e.target.checked)}
                    style={{
                      padding: '8px 16px',
                      borderRadius: '16px',
                      border: '1px solid var(--border-light)',
                      backgroundColor: customRules.tags.includes(tag.id) ? 'var(--accent-primary)' : 'var(--primary-bg)',
                      color: customRules.tags.includes(tag.id) ? '#fff' : 'var(--text-primary)'
                    }}
                  >
                    {tag.name}
                  </Checkbox>
                ))}
              </div>
            </div>

            {/* 菜品搜索 */}
            <div style={{ marginBottom: '24px' }}>
              <Input
                placeholder="搜索菜品名称"
                value={customRules.searchKeyword}
                onChange={handleSearchChange}
                style={{ marginBottom: '12px' }}
              />
            </div>

            {/* 菜品选择 */}
            <div style={{ marginBottom: '16px' }}>
              <Text style={{ fontSize: '16px', fontWeight: 500, marginBottom: '12px', display: 'block' }}>
                选择菜品
              </Text>
              {loadingDishes ? (
                <Spin size="small" />
              ) : (
                <div style={{ maxHeight: '200px', overflowY: 'auto', border: '1px solid var(--border-light)', borderRadius: '8px', padding: '8px' }}>
                  {filteredDishes.length > 0 ? (
                    filteredDishes.map(dish => (
                      <div key={dish.id} style={{ display: 'flex', alignItems: 'center', marginBottom: '8px', padding: '8px', borderRadius: '8px', backgroundColor: 'var(--primary-bg)' }}>
                        <Checkbox
                          checked={customRules.selectedDishes.includes(dish.id)}
                          onChange={(e) => handleDishSelect(dish.id, e.target.checked)}
                          style={{ marginRight: '12px' }}
                        />
                        <div style={{ flex: 1 }}>
                          <Text style={{ fontWeight: 500 }}>{dish.name}</Text>
                          <div style={{ display: 'flex', gap: '4px', marginTop: '4px' }}>
                            <Tag size="small" style={{ backgroundColor: 'var(--tertiary-bg)' }}>
                              {getCategoryName(dish.categoryId)}
                            </Tag>
                            {dish.tags && dish.tags.map(tagId => (
                              <Tag key={tagId} size="small" style={{ backgroundColor: 'rgba(26, 115, 232, 0.1)', color: 'var(--accent-primary)' }}>
                                {getTagName(tagId)}
                              </Tag>
                            ))}
                          </div>
                        </div>
                      </div>
                    ))
                  ) : (
                    <div style={{ textAlign: 'center', padding: '20px', color: 'var(--text-secondary)' }}>没有找到匹配的菜品</div>
                  )}
                </div>
              )}
            </div>
          </div>
        </Drawer>
      </div>

      <LoginModal
        visible={loginVisible}
        onCancel={() => setLoginVisible(false)}
        onSuccess={handleLogin}
      />
    </div>
  );
};

export default RandomPage;